package com.omkarpatil.learningjpa2.mapping.onetoone.jointable;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import com.omkarpatil.learningjpa2.util.EntityManagerFactoryFactory;

public class TestDriver {

	public static void main(String[] args) {
		/* Creating a person */
		EntityManager em1 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em1.getTransaction().begin();
		
		System.out.println("##### Adding desk to database ...");
		Desk desk = new Desk("I6PL06");
		em1.persist(desk);
		
		System.out.println("##### Adding Employee to database ...");
		Employee emp1 = new Employee("Omkar Patil");
		emp1.setDesk(desk);
		
		em1.persist(emp1);
		
		em1.getTransaction().commit();
		em1.close();
		
		int empId = emp1.getId();
		
		System.out.println("##### Getting employee to check his desk number ...");
		EntityManager em2 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em2.getTransaction().begin();
		
		Employee emp2 = em2.find(Employee.class, empId);
		
		System.out.printf("##### Desk number for employee %s : %s\n", emp2.getName(), emp2.getDesk().getNumber());
		
		System.out.println("##### trying to associate another employee with same desk ...");
		try {
			Employee emp3 = new Employee("Mr. French");
			emp3.setDesk(emp2.getDesk());
			em2.persist(emp3);
		} catch (PersistenceException e) {
			System.out.println("##### Can't do that! It's One to One association ...");
		}
		em2.getTransaction().commit();
		em2.close();
	}

}
